/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TemplateFrm.java
 *
 * Created on 2011-12-28, 14:30:15
 */
package databasehelp;

import com.breeze.util.StringUtil;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;

/**
 *
 * @author huateng
 */
public class TemplateFrm extends javax.swing.JFrame {

    /** Creates new form TemplateFrm */
    public TemplateFrm() {
        initComponents();
        initText();
        pane.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent ke){
                System.out.println("aa");
                String text=pane.getText();
                int pos=pane.getCaretPosition();
                pane.setText("");
                pane.setText(text);
                pane.setCaretPosition(pos);
                coloredText(text);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        pane = new JTextPane(){
            public boolean getScrollableTracksViewportWidth(){
                return false;
            }
            public void setSize(Dimension d){
                if(d.width<getParent().getSize().width){
                    d.width=getParent().getSize().width;
                }
                d.width+=100;
                super.setSize(d);
            }
        };
        btn_OK = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        pane.setName("pane"); // NOI18N
        jScrollPane1.setViewportView(pane);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(databasehelp.DatabaseHelpApp.class).getContext().getResourceMap(TemplateFrm.class);
        btn_OK.setText(resourceMap.getString("btn_OK.text")); // NOI18N
        btn_OK.setName("btn_OK"); // NOI18N
        btn_OK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_OKActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btn_OK, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 635, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btn_OK, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_OKActionPerformed
        try {
            // TODO add your handling code here:
            FileWriter fw=new FileWriter(TEMPLATE_FILE_LOCATION);
            fw.write(pane.getText());
            fw.flush();
            fw.close();
            this.dispose();
        } catch (IOException ex) {
            Logger.getLogger(TemplateFrm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btn_OKActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TemplateFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TemplateFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TemplateFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TemplateFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TemplateFrm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_OK;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane pane;
    // End of variables declaration//GEN-END:variables
    public static final String XML_PATTERN = "<|>";
    public static final String CONFIG_PATTERN = "\\{\\^|\\^\\}";
    public static final String OGNL_PATTERN="\\$\\{.*?\\}|\\$\\%\\{.*?\\}";
    public static Color XML_COLOR = Color.yellow;
    public static Color CONFIG_COLOR = Color.cyan;
    public static Color OGNL_COLOR=Color.lightGray;
    public static final String TEMPLATE_FILE_LOCATION = "src/test/template.xml";

    private void initText() {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(TEMPLATE_FILE_LOCATION));
            StringBuilder sb = new StringBuilder();
            String str = null;
            while (reader.ready()) {
                str = reader.readLine();
                sb.append(str).append("\n");
            }
            pane.setText(sb.toString());
            coloredText(sb.toString());
        } catch (IOException ex) {
            Logger.getLogger(TemplateFrm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void coloredText(String str) {
        int[][] xml_index = StringUtil.getMatchedIndex(str, XML_PATTERN);
        int[][] config_index = StringUtil.getMatchedIndex(str, CONFIG_PATTERN);
        int[][] ognl_index=StringUtil.getMatchedIndex(str, OGNL_PATTERN);

        if (xml_index != null) {
            for (int i = 0; i < xml_index.length; i++) {
                try {
                    pane.getHighlighter().addHighlight(xml_index[i][0], xml_index[i][1], new DefaultHighlighter.DefaultHighlightPainter(XML_COLOR));
                } catch (BadLocationException ex) {
                    Logger.getLogger(TemplateFrm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if (config_index != null) {
            for (int i = 0; i < config_index.length; i++) {
                try {
                    pane.getHighlighter().addHighlight(config_index[i][0], config_index[i][1], new DefaultHighlighter.DefaultHighlightPainter(CONFIG_COLOR));
                } catch (BadLocationException ex) {
                    Logger.getLogger(TemplateFrm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
         if (ognl_index != null) {
            for (int i = 0; i < ognl_index.length; i++) {
                try {
                    pane.getHighlighter().addHighlight(ognl_index[i][0], ognl_index[i][1], new DefaultHighlighter.DefaultHighlightPainter(OGNL_COLOR));
                } catch (BadLocationException ex) {
                    Logger.getLogger(TemplateFrm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
